How do I use the finally section in a pipeline as code?
The finally section in a pipeline as code allows you to define a job that will always be executed regardless of the success or failure of previous jobs in the pipeline. This is useful when you need to perform cleanup tasks or final actions, such as sending notifications or generating reports, after the pipeline execution.
To use the finally section in your pipeline as code, follow these steps:
Define a job within the finally section in your pipeline YAML file. For example:
finally:
cleanup:
script:
- echo "Performing cleanup tasks..."
- send_notification.sh
Specify the desired script or commands within the script section of the finally job. This can include any necessary cleanup tasks, notifications, or additional actions you want to perform.
Ensure that the finally job is properly indented under the finally section and has a unique name. You can have multiple finally jobs if needed, each with its own name and set of tasks.
Here's an example of a complete pipeline YAML file that includes a finally section:
stages:
- build
- test
- deploy
job1:
stage: build
script:
- echo "Building the project..."
job2:
stage: test
script:
- echo "Running tests..."
job3:
stage: deploy
script:
- echo "Deploying the application..."
finally:
cleanup:
script:
- echo "Performing cleanup tasks..."
- send_notification.sh
In this example, the cleanup job within the finally section will always be executed at the end of the pipeline, regardless of the success or failure of the previous jobs. It can be used to perform any necessary cleanup tasks or final actions.
By using the finally section, you can ensure that important cleanup tasks or actions are executed consistently, even if the pipeline encounters errors or failures along the way. This helps maintain the integrity and reliability of your pipeline and ensures that necessary actions are taken regardless of the pipeline outcome.